<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class RepayReliefRecordModel extends Model
{
    /**
     * 与模型关联的数据表。
     *
     * @var string
     * @throws \Throwable
     */
    protected $table = 'repay_relief_records';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['loan_id', 'period', 'relief_amount', 'deadline'];

    const STATUS_UNUSED  = 1; // 未使用
    const STATUS_EXPIRED = 2; // 已过期
    const STATUS_USED = 3; // 已使用

    /**
     * 根据新流订单号，分期 获取总减免金额
     * @param $loan_id
     * @param $period
     * @return int
     * @throws \Throwable
     */
    public static function getReliefAmount($loan_id, $period)
    {
        $date = date('Y-m-d H:i:s');
        self::clearData();
        return self::where('status', self::STATUS_UNUSED)
            ->where('loan_id', $loan_id)
            ->where('period', $period)
            ->where('deadline', '>',$date)
            ->sum('relief_amount');
    }

    /**
     * 根据新流订单号，分期 设置减免金额为已使用
     * @param $loan_id
     * @param $period
     * @return int
     * @throws \Throwable
     */
    public static function setReliefUsed($loan_id, $period)
    {
        $date = date('Y-m-d H:i:s');
        self::clearData();
        return self::where('status', self::STATUS_UNUSED)
            ->where('loan_id', $loan_id)
            ->where('period', $period)
            ->where('deadline', '>',$date)
            ->update(['status' => self::STATUS_USED]);
    }

    /**
     * 清洗已过期的数据 分为自动(默认)、手动
     * @param string $type
     * @param array $list
     * @return mixed|null
     * @throws \Throwable
     */
    protected static function clearData($type = 'auto', $list = [])
    {
        switch ($type) {
            case 'auto':
                $list = self::where('status', self::STATUS_UNUSED)
                    ->get();
                $time = time();
                return \DB::transaction(function () use($list, $time){
                    foreach ($list as $item) {
                        if(strtotime($item->deadline) < $time) {
                          self::where(['id' => $item['id']])
                                ->update([
                                    'status' => self::STATUS_EXPIRED,
                                ]);
                        }
                    }
                });
                break;
            default:
                return null;
                break;
        }
    }

    /**
     * Description: 获取减免费
     * Author: Gxs
     * @param $value
     * @return int
     */
    public function getReliefAmountAttribute($value)
    {
        return bcdiv($value, 100, 2);
    }




}
